package com.wei.czz.framework.admin.controller;

import com.wei.czz.common.annotation.AuthLogin;
import com.wei.czz.common.dto.admin.userLoginFlow.UserLoginFlowDto;
import com.wei.czz.common.enums.ResultEnum;
import com.wei.czz.common.enums.admin.user.LoginTypeEnum;
import com.wei.czz.common.enums.admin.user.RequestChannelEnum;
import com.wei.czz.common.tool.PageDto;
import com.wei.czz.common.tool.Result;
import com.wei.czz.common.utils.CopyUtils;
import com.wei.czz.framework.admin.entity.UserLoginFlowEntity;
import com.wei.czz.framework.admin.service.UserLoginFlowService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2024-06-14 09:44:10
 * className: UserLoginFlowController
 * version: 1.0
 * description:
 */
@RestController
@RequestMapping("/user-login-flow")
@AllArgsConstructor
public class UserLoginFlowController {

    private static final Logger log = LoggerFactory.getLogger(UserLoginFlowController.class);

    private final UserLoginFlowService userLoginFlowService;

    /**
     * 分页获取用户登录流水接口
     * @param page 页码
     * @return 结果
     */
    @GetMapping("/page/list")
    @AuthLogin
    public Result<PageDto<UserLoginFlowDto>> getUserLoginFlowPageList(@RequestParam("page") Integer page) {
        log.info("开始分页获取用户登录流水业务。page={}", page);

        if (page <= 0) {
            log.info("页码参数小于等于零");
            return Result.paramFail();
        }
        if (page > 10) {
            log.info("页码参数大于十");
            return Result.getResult(ResultEnum.REQUEST_FAIL.getCode(), "只允许查询最近一百条登录记录");
        }

        PageDto<UserLoginFlowEntity> pageDto = userLoginFlowService.getPageList(page);

        // 封装返回
        PageDto<UserLoginFlowDto> result = pageDto.rebuild();
        if (!pageDto.isEmpty()) {
            List<UserLoginFlowEntity> userLoginFlowList = pageDto.getList();

            List<UserLoginFlowDto> list = CopyUtils.mapList(userLoginFlowList, userLoginFlow -> {
                UserLoginFlowDto userLoginFlowDto = CopyUtils.map(userLoginFlow, UserLoginFlowDto.class);
                userLoginFlowDto.setChannelName(RequestChannelEnum.getNickName(userLoginFlow.getChannel()))
                        .setTypeName(LoginTypeEnum.getName(userLoginFlow.getType()));
                return userLoginFlowDto;
            });
            // 封装返回
            result = pageDto.rebuild(list);
        }

        log.info("分页获取用户登录流水业务结束");
        return Result.success(result);
    }
}
